# !/usr/bin/env python3
# -*- coding: utf-8 -*-
###----------------------------------------------------1、文件说明----------------------------------------------------###
'''
* 说明：操作pdf的库的学习笔记
* 时间：2021-1-18
* 文件：
* 作者：whg
* 备注：
'''
###----------------------------------------------------2、库导入----------------------------------------------------###
from PyPDF2 import PdfFileReader, PdfFileWriter
###----------------------------------------------------3、参数配置----------------------------------------------------###
###----------------------------------------------------4、主体程序----------------------------------------------------###

class WPdf(object):
    '''
    操作pdf的类
    '''
    def __init__(self, filename=""):
        '''
        文档初始化
        :param filename:
        '''
        self.filename = filename
        self.pdf = PdfFileReader(self.filename)

    def GetPageNum(self):
        '''
        获取pdf的页数
        :return:
        '''
        self.pagenum = self.pdf.getNumPages()
        return self.pagenum

    def WriteFile(self, pdf=None, filename="out.pdf"):
        '''
        将pdf输出来文件中
        :param pdf:外部获取的PDF句柄
        :param filename: pdf的文件名字
        :return:
        '''
        if not pdf:
            pdf = self.pdf
        pdf_write = PdfFileWriter()
        for i in range(self.GetPageNum()):
            pdf_write.addPage(pdf.getPage(i))
        with open(filename, 'wb') as file:
            pdf_write.write(file)

    def GetPdf(self):
        '''
        返回打开PDF的句柄
        :return:
        '''
        return self.pdf



if __name__ == '__main__':
    print('Start Program...\r\n')
    spdf = WPdf("demo.pdf")
    spdf.WriteFile()
    print('\nSuccess ...')